package com.xn.app.muying.util;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.FileProvider;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.webkit.URLUtil;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.xn.app.muying.activity.MuYingApplication;
import com.xn.app.muying.R;

import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import okhttp3.Request;

/**
 * 版本更新
 *
 * @author Android
 */
public class UpdateManager {
    /* 下载中 */
    private static final int DOWNLOAD = 1;
    /* 下载结束 */
    private static final int DOWNLOAD_FINISH = 2;
    /* 下载失败 */
    private static final int DOWNLOAD_FAIL = 3;
    /* 获取服务端版本号失败 */
    private static final int GETVERSION_FAIL = 4;
    /* 下载保存路径 */
    private String mSavePath = null;
    /* 记录进度条数量 */
    private int progress = 0;
    /* 是否取消更新 */
    private boolean cancelUpdate = false;
    private Context mContext = null;
    private Activity mActivity = null;
    /* 更新进度条 */
    private ProgressBar mProgress = null;
    private MyAlertDialog mDownloadDialog = null;
    /**
     * 接收APK下载路径
     */
    private String URL = "";
    //更新内容
    private String upDataString = "";
    // 服务器版本号
    String serviceCode = "";
    //加载框
    MyAlertDialog dialog = null;
    //记录当前是wifi下自动下载，还是用户手动点击下载    false为用户手动下载
    private boolean lean=false;
    //判断是强制更新还是非强制
    private int force=0;

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                // 正在下载
                case DOWNLOAD:
                    // 用户手动更新，设置进度条位置
                    if(!lean){
                        mProgress.setProgress(progress);
                    }
                    break;
                case DOWNLOAD_FINISH:
                    // 安装文件
                    if(!lean){
                        installApk();
                    }else{
                        showNoticeDialog();
                    }

                    break;
                case DOWNLOAD_FAIL:
                    // 提示失败
                    ToastUtil.showToast(mContext, "下载更新包失败");
                    // 取消下载对话框显示
                    if(mDownloadDialog!=null){
                        mDownloadDialog.dismissOut();
                    }
                    break;
                case GETVERSION_FAIL:
                    // 提示失败
                    ToastUtil.showToast(mContext, msg.obj.toString());
                    break;
                case 5:
                    //下载完成
                    if(!lean){
                        //流量下载
                        ToastUtil.showToast(mContext, "下载更新包完成，正在准备安装");
                        // 取消下载对话框显示
                        if(mDownloadDialog!=null){
                            mDownloadDialog.dismissOut();
                        }
                    }
                    break;
                default:
                    break;
            }
        }

        ;
    };

    public UpdateManager(Context context, Activity activity) {
        this.mContext = context;
        this.mActivity = activity;
    }

    /**
     * 检测软件更新
     *
     * @throws Exception
     */
    public void checkUpdate() {
        isUpdate();
    }

    /**
     * 检查软件是否有更新版本
     *
     * @return
     * @throws Exception
     */
    private void isUpdate() {

        new Thread(new Runnable() {

            @Override
            public void run() {
                // 获取当前软件版本
                String versionCode = getVersion(mContext);
                try {
                    Request request = new Request.Builder().url(APIMethod.UpdataManager).get().build();
                    okhttp3.Response response = null;
                    response = MuYingApplication.mOkHttpClient.newCall(request).execute();
                    int code = response.code();
                    String bodys = response.body().string();
                    if (code == 200 || code == 204) {
                        JSONObject jsonObject = new JSONObject(bodys);
                        URL = jsonObject.getString("url");
                        upDataString = jsonObject.getString("description");
                        serviceCode = jsonObject.getString("version");
                        force= jsonObject.getInt("force");
                    } else {
                        // 通过调用handler来通知UI主线程更新UI,
                        Message message = new Message();
                        message.obj = "获取服务端版本号失败!";
                        message.what = GETVERSION_FAIL;
                        mHandler.sendMessage(message);
                    }
                    if (!"".equals(serviceCode) && !serviceCode.equals(versionCode)) {
                        loginHandler.sendEmptyMessage(1);
                    } else {
                        loginHandler.sendEmptyMessage(2);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }


    /**
     * 获取线程返回的数据，更新UI组件
     */
    @SuppressLint("HandlerLeak")
    Handler loginHandler = new Handler() {
        public void handleMessage(Message msg) {

            switch (msg.what) {
                case 1:
                    //检测手机是否有读写权限
                    verifyStoragePermissions(mActivity);
                    break;
                case 2:
                    break;
                default:
                    break;
            }
        }
    };

    /**
     * 获取版本号
     */
    public static String getVersion(Context context) {
        String versionname;
        try {
            PackageManager pm = context.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
            versionname = pi.versionName;// 获取在AndroidManifest.xml中配置的版本号
        } catch (PackageManager.NameNotFoundException e) {
            versionname = "";
        }
        return versionname;
    }

    /**
     * 显示软件更新对话框
     */
    private void showNoticeDialog() {
        //true为弹出框可以取消   false为不可取消
        boolean forceLean=true;
        try {
            if (dialog == null) {
                //加载弹出框
                dialog = new MyAlertDialog();
                //如果为强制更新，则不显示取消按钮
                if(force!=0){
                    //强制，更新弹框不可以取消
                    forceLean=false;
                }
                dialog.upDate_Dialog(mContext, R.layout.update_dialog,forceLean);
                //如果是强制，则不显示取消按钮
                if(forceLean){//
                    //设置取消按钮
                    ImageView getClose = dialog.getClose();
                    getClose.setVisibility(View.VISIBLE);
                    getClose.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            dialog.dismissOut();
                        }
                    });
                }
                //设置标题
                TextView ServiceCodeTV = dialog.getServiceCode();
                ServiceCodeTV.setText("V" + serviceCode);
                //设置内容
                TextView data = dialog.getData();
                data.setText(upDataString);
                //设置确认按钮
                TextView getConfirm_text = dialog.getConfirm_text();
                if(lean){
                    //如果是wifi下载好的
                    getConfirm_text.setText("下载完成，点击安装");
                    getConfirm_text.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            dialog.dismissOut();
                            installApk();
                        }
                    });
                }else{
                    //如果是流量下载
                    getConfirm_text.setText("立即更新");
                    getConfirm_text.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            dialog.dismissOut();
                            showDownloadDialog();
                        }
                    });
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 显示软件下载对话框
     */
    @SuppressLint("InflateParams")
    private void showDownloadDialog() {
        // 构造软件下载对话框
        //加载弹出框
        mDownloadDialog = new MyAlertDialog();
        mDownloadDialog.upDate_item_Dialog(mContext, R.layout.update_dialog_item);
        //取消按钮
        TextView data = mDownloadDialog.getData();
        data.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mDownloadDialog.dismissOut();
                // 设置取消状态
//                cancelUpdate = true;
            }
        });
        //获取进度条
        mProgress = mDownloadDialog.getProgressBar();
        // 下载文件
        downloadApk();
    }

    /**
     * 下载apk文件
     */
    private void downloadApk() {
        // 启动新线程下载软件
        new downloadApkThread().start();
    }

    /**
     * 下载文件线程
     */
    int length = 0;

    private class downloadApkThread extends Thread {
        @SuppressLint({"WorldWriteableFiles", "WorldReadableFiles"})
        @SuppressWarnings("deprecation")
        @Override
        public void run() {
            try {
                File file = null;
                FileOutputStream fos = null;
                // 判断SD卡是否存在，并且是否具有读写权限
                if (Environment.getExternalStorageState().equals(
                        Environment.MEDIA_MOUNTED)) {
                    // 获得存储卡的路径
                    mSavePath =Environment.getExternalStorageDirectory() + "/temp";
                    file = new File(mSavePath);
                    // 判断文件目录是否存在
                    if (!file.exists()) {
                        file.mkdir();
                    }
                    File apkFile = new File(file, "MuYing.apk");
                    fos = new FileOutputStream(apkFile);
                } else {
                    fos = mContext.openFileOutput("MuYing.apk",
                            Context.MODE_WORLD_READABLE
                                    | Context.MODE_WORLD_WRITEABLE);
                }
                String downLoadAddr = URL;
                if (!URLUtil.isNetworkUrl(downLoadAddr)) {
                    ToastUtil.showToast(mContext, "下载地址错误！");
                } else {
                    java.net.URL url = new URL(downLoadAddr);
                    // 创建连接
                    HttpURLConnection conn = (HttpURLConnection) url
                            .openConnection();
                    conn.setRequestProperty("Accept-Encoding", "identity");
                    conn.connect();
                    // 创建输入流
                    InputStream is = conn.getInputStream();
                    // 获取文件大小
                    length = conn.getContentLength();
                    int count = 0;
                    // 缓存
                    byte buf[] = new byte[128];

                    // 写入到文件中
                    do {
                        int numread = is.read(buf);
                        //用户手动更新，显示进度条
                        if(!lean){
                            mProgress.setMax(length);// 设置进度条的最大刻度
                        }
                        count += numread;
                        // 计算进度条位置
                        progress = count;
                        // 更新进度
                        mHandler.sendEmptyMessage(DOWNLOAD);
                        if (numread <= 0) {
                            // 下载完成
                            mHandler.sendEmptyMessage(5);
                            for (int i = 0; i < 3; i++) {
                                Thread.sleep(1000);
                            }
                            mHandler.sendEmptyMessage(DOWNLOAD_FINISH);
                            break;
                        }
                        // 写入文件
                        fos.write(buf, 0, numread);
                    } while (!cancelUpdate);// 点击取消就停止下载.
                    fos.close();
                    is.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
                // 下载失败
                mHandler.sendEmptyMessage(DOWNLOAD_FAIL);
            }
        }
    }

    ;

    /**
     * 安装APK文件
     */

    private void installApk() {
        File apkfile = null;
        // 判断SD卡是否存在，并且是否具有读写权限
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            apkfile = new File(mSavePath, "MuYing.apk");
        } else {
            apkfile = new File(mContext.getFilesDir(), "MuYing.apk");
        }
        if (!apkfile.exists()) {
            return;
        }
        // 通过Intent安装APK文件
        Intent i = new Intent(Intent.ACTION_INSTALL_PACKAGE);
        //如果版本大于等于androidN
        Uri photoURI = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            photoURI = FileProvider.getUriForFile(mContext, "com.xn.app.muying.fileProvider", apkfile);
            i.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        } else {
            photoURI = Uri.parse("file://" + apkfile.toString());
            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        i.setDataAndType(photoURI,
                "application/vnd.android.package-archive");
        mContext.startActivity(i);
            android.os.Process.killProcess(android.os.Process.myPid());
    }

    // Storage Permissions
    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE};

    /**
     * Checks if the app has permission to write to device storage
     * <p>
     * If the app does not has permission then the user will be prompted to
     * grant permissions
     *
     * @param activity
     */
    public void verifyStoragePermissions(Activity activity) {
        // Check if we have write permission
        int permission1 = ActivityCompat.checkSelfPermission(activity,
                Manifest.permission.WRITE_EXTERNAL_STORAGE);
        int permission2= ActivityCompat.checkSelfPermission(activity,
                Manifest.permission.READ_EXTERNAL_STORAGE);
        if (permission1 != PackageManager.PERMISSION_GRANTED&&permission2!= PackageManager.PERMISSION_GRANTED) {
            // We don't have permission so prompt the user
            ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE,
                    REQUEST_EXTERNAL_STORAGE);
        } else {
            //判断wifi是否连接，如果连接wifi，则直接下载，否则提示用户是否下载
            if(NetworkUtil.isWIFIConnected(mContext)){
                lean=true;
                // 下载文件
                downloadApk();
            }else{
                lean=false;
                // 显示提示对话框
                showNoticeDialog();
            }
        }
    }
}